#!/usr/bin/python
# -*- coding: utf-8 -*-
#coding=utf-8

import json
import datetimeDemo as tsLog
def demo():
    # https://www.runoob.com/python3/python3-json.html
    tsLog.logTs("jsonDemo", preNewLineNum=2)

    monthArr = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
                "November", "December"]

    monthDic = {
        "January":31,
        "February": 28,
        "March": 31,
        "April": 30,
        "May": 31,
        "June": 30,
        "July": 31,
        "August": 31,
        "September": 30,
        "October": 31,
        "November": 30,
        "December": 31}

    testDic = {"arr": monthArr,
               "dic": monthDic,
               "int": 123,
               "float": 12.34,
               "bool-true": True,
               "bool-false": False,
               "tuple": (123, '123', [1, 2, 3], {1:2, 2:3, 3:4}),
               "str": "zhang"}
    print("testDic", testDic)

    # list/字典 --》 json.dumps --》json字符串
    jsonStr = json.dumps(testDic)
    print("jsonStr", jsonStr)
    print("listJsonStr", json.dumps(monthArr))

    # json字符串 --》 json.loads --》list/字典
    dicJsonStr = '{"arr": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "dic": {"January": 31, "February": 28, "March": 31, "April": 30, "May": 31, "June": 30, "July": 31, "August": 31, "September": 30, "October": 31, "November": 30, "December": 31}, "int": 123, "float": 12.34, "tuple": [123, "123", [1, 2, 3], {"1": 2, "2": 3, "3": 4}], "str": "zhang"}'
    print("dicJsonStr", dicJsonStr)

    dicFromJson = json.loads(dicJsonStr)
    print("dicFromJson", type(dicFromJson), dicFromJson)

    listJsonStr = '[123, "123", [1, 2, 3], {"1":2, "2":3, "3":4}]'
    print("listJsonStr", listJsonStr)

    listFromJson = json.loads(listJsonStr)
    print("listFromJson", type(listFromJson), listFromJson)

    # json.loads 对于不合法的json 将报错，可以将它包裹在 try except 中
    fakeJsonStr = '[123, "123", [1, 2, 3], {"1":2, "2":3, "3":4'
    print("fakeJsonStr", fakeJsonStr)
    try:
        objFromJson = json.loads(fakeJsonStr)
        print("parse Json succ", type(objFromJson), objFromJson)
    except Exception as err:
        print("parse Json fail", type(err), err)




if __name__ == '__main__':
    demo()